package com.lzb.play.fragment;

import static android.app.Activity.RESULT_OK;

import android.Manifest;
import android.content.Intent;
import android.graphics.Color;
import android.net.Uri;
import android.os.Bundle;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.GridLayoutManager;

import android.os.Handler;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import com.blankj.utilcode.util.AppUtils;
import com.blankj.utilcode.util.FileUtils;
import com.blankj.utilcode.util.PermissionUtils;
import com.blankj.utilcode.util.SPUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.blankj.utilcode.util.UriUtils;
import com.blankj.utilcode.util.UtilsTransActivity;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.listener.OnItemClickListener;
import com.lzb.play.BaseNoModelFragment;
import com.lzb.play.Content;
import com.lzb.play.R;
import com.lzb.play.activity.GridSettingActivity;
import com.lzb.play.activity.PianoSettingActivity;
import com.lzb.play.adapter.GridAdapter;
import com.lzb.play.basic.media.AudioPlayerImpl;
import com.lzb.play.basic.media.IAudioPlayer;
import com.lzb.play.basic.utils.FileUtil;
import com.lzb.play.bean.GridBean;
import com.lzb.play.databinding.FragmentRhythmGridBinding;
import com.lzb.play.dialog.PermissionExplainDialog;
import com.lzb.play.dialog.RecordSaveDialog;
import com.lzb.play.utils.AppSpUtils;
import com.lzb.play.utils.MyAudioPlayerImpl;
import com.lzb.play.utils.MyMediaRecorder;

import java.lang.annotation.Target;
import java.util.ArrayList;
import java.util.List;

/**
 * A simple {@link Fragment} subclass.
 * Use the {@link RhythmGridFragment#newInstance} factory method to
 * create an instance of this fragment.
 */
public class RhythmGridFragment extends BaseNoModelFragment<FragmentRhythmGridBinding> implements View.OnClickListener, OnItemClickListener {

    private List<GridBean> listShow = new ArrayList<>();
    private GridAdapter gridAdapter;
    private List<MyAudioPlayerImpl> listPlay = new ArrayList<>();
    private boolean isRecord;
    private MyMediaRecorder mRecorder;


    @Override
    protected int onCreate() {
        return R.layout.fragment_rhythm_grid;
    }

    @Override
    protected void initView() {
        mDataBinding.ivSetGrid.setOnClickListener(this);
        mDataBinding.tvResetGrid.setOnClickListener(this);
        mDataBinding.ivRecord.setOnClickListener(this);
        mDataBinding.tvSpeed1.setOnClickListener(this);
        mDataBinding.tvSpeed2.setOnClickListener(this);
        mDataBinding.tvSpeed3.setOnClickListener(this);
        mDataBinding.tvSpeed4.setOnClickListener(this);

        mRecorder = new MyMediaRecorder();

        mDataBinding.rvGridList.setLayoutManager(new GridLayoutManager(mContext, 5));
        gridAdapter = new GridAdapter();
        mDataBinding.rvGridList.setAdapter(gridAdapter);
        gridAdapter.setOnItemClickListener(this);
    }

    @Override
    public void onClick(View view) {
        int id = view.getId();
        if (id == R.id.ivSetGrid || id == R.id.tvResetGrid) {//设置网格/重置网格
            Intent intent = new Intent(getActivity(), GridSettingActivity.class);
            startActivityForResult(intent, 1001);
        } else if (id == R.id.ivRecord) {//录音
            if (!isRecord) {
                getPermission();
            } else {
                isRecord = false;
                mRecorder.stopRecording();
                showRecordSaveDialog();
            }
            mDataBinding.ivRecord.setImageResource(isRecord ? R.drawable.icon_record_select : R.drawable.icon_record_no);
        } else if (id == R.id.tvSpeed1) {//0.5x
            clearSelection();
            mDataBinding.tvSpeed1.setBackgroundResource(R.drawable.grid_speed_sel);
            setVolume(0.5f);
        } else if (id == R.id.tvSpeed2) {//1x
            clearSelection();
            mDataBinding.tvSpeed2.setBackgroundResource(R.drawable.grid_speed_sel);
            setVolume(1f);
        } else if (id == R.id.tvSpeed3) {//1.5x
            clearSelection();
            mDataBinding.tvSpeed3.setBackgroundResource(R.drawable.grid_speed_sel);
            setVolume(1.5f);
        } else if (id == R.id.tvSpeed4) {//2x
            clearSelection();
            mDataBinding.tvSpeed4.setBackgroundResource(R.drawable.grid_speed_sel);
            setVolume(2f);
        }
    }

    @Override
    public void onItemClick(@NonNull BaseQuickAdapter<?, ?> adapter, @NonNull View view, int position) {
        if (gridAdapter.getItem(position).isSetting()) {
            playAudio(position);
        } else {
            ToastUtils.showShort(getString(R.string.please_set_bird));
        }
    }

    @Override
    protected void initData() {
        for (int i = 0; i < 20; i++) {
            MyAudioPlayerImpl audioPlayer = new MyAudioPlayerImpl();
            audioPlayer.setHasLoop(true);
            listPlay.add(audioPlayer);
        }
        getData();
    }

    private void getData() {
        listShow.clear();
        List<GridBean> listSp = AppSpUtils.getGridList();
        if (listSp != null && listSp.size() > 0) {
            listShow.addAll(listSp);
            for (GridBean gridBean : listShow) {
                if (gridBean.isSetting()) {
                    mDataBinding.ivSetGrid.setVisibility(View.VISIBLE);
                    mDataBinding.llResetGrid.setVisibility(View.GONE);
                }
                break;
            }
            mDataBinding.ivSetGrid.setVisibility(View.GONE);
            mDataBinding.llResetGrid.setVisibility(View.VISIBLE);
        } else {
            listSp = new ArrayList<>();
            for (int i = 0; i < 20; i++) {
                listSp.add(new GridBean(0, false, false));
            }
            AppSpUtils.saveGridList(listSp);
            listShow.addAll(listSp);
            mDataBinding.ivSetGrid.setVisibility(View.VISIBLE);
            mDataBinding.llResetGrid.setVisibility(View.GONE);
        }
        gridAdapter.setList(listShow);
    }

    private void playAudio(int position) {
        if (listPlay.get(position).isPlaying()) {
            listPlay.get(position).pause();
            gridAdapter.getItem(position).setSelected(false);
        } else {
            Uri uri = Uri.parse("android.resource://" + AppUtils.getAppPackageName() + "/" + listShow.get(position).getRawId());
            listPlay.get(position).play(UriUtils.uri2File(uri).getPath());
            gridAdapter.getItem(position).setSelected(true);
        }
        gridAdapter.notifyItemChanged(position);
    }

    private void getPermission() {
        PermissionExplainDialog dialog = new PermissionExplainDialog(mContext);
        dialog.setContent(getString(R.string.get_record_permission));
        PermissionUtils.permission(Manifest.permission.RECORD_AUDIO).explain(new PermissionUtils.OnExplainListener() {
            @Override
            public void explain(@NonNull UtilsTransActivity activity, @NonNull List<String> denied, @NonNull ShouldRequest shouldRequest) {
                dialog.show();
                new Handler().postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        shouldRequest.start(true);
                    }
                }, 500);
            }
        }).callback(new PermissionUtils.SimpleCallback() {
            @Override
            public void onGranted() {
                dialog.dismiss();
                startRecord();
            }

            @Override
            public void onDenied() {
                dialog.dismiss();
            }
        }).request();
    }

    //开始录音
    private void startRecord() {
        String musicPath = FileUtil.generateFilePath(Content.Temp, ".mp3");
        try {
            isRecord = true;
            mRecorder.setMyRecAudioFile(FileUtils.getFileByPath(musicPath));
            if (!mRecorder.startRecorder()) {
                isRecord = false;
                ToastUtils.showShort(R.string.audio_fail_tips);
            }
        } catch (Exception e) {
            isRecord = false;
            ToastUtils.showShort(R.string.audio_fail_tips2);
            e.printStackTrace();
        }
        mDataBinding.ivRecord.setImageResource(isRecord ? R.drawable.icon_record_select : R.drawable.icon_record_no);
    }

    private void showRecordSaveDialog() {
        RecordSaveDialog dialog = new RecordSaveDialog(mContext);
        dialog.setAudioPath(mRecorder.getMyRecAudioFile().getPath());
        dialog.show();
    }

    private void setVolume(float volume) {
        for (IAudioPlayer audioPlayer : listPlay) {
            audioPlayer.setSpeed(volume);
        }
    }

    @Override
    public void onPause() {
        super.onPause();
        for (IAudioPlayer audioPlayer : listPlay) {
            if (audioPlayer.isPlaying()) {
                audioPlayer.pause();
            }
        }
        for (GridBean gridBean : listShow) {
            gridBean.setSelected(false);
        }
        gridAdapter.setList(listShow);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        for (IAudioPlayer audioPlayer : listPlay) {
            audioPlayer.stop();
        }
    }

    private void clearSelection() {
        mDataBinding.tvSpeed1.setBackgroundResource(0);
        mDataBinding.tvSpeed2.setBackgroundResource(0);
        mDataBinding.tvSpeed3.setBackgroundResource(0);
        mDataBinding.tvSpeed4.setBackgroundResource(0);
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == 1001 && resultCode == RESULT_OK && data != null) {
            getData();
        }
    }

}